let express = require('express')
let router = express.Router()

let multer = require('multer')
let fs = require('fs')
let path = require('path')
let mysqlHelper = require('../utils/mysqlHelper.js')
let PDFImage = require("pdf-image").PDFImage

let upload = multer({
    storage: multer.diskStorage({
        // 设置文件存储位置
        destination: function (req, file, callback) {
            let date = new Date()
            let year = date.getFullYear()
            let month = (date.getMonth() + 1).toString().padStart(2, '0')
            let day = date.getDate()
            let dir = './uploads/' + year + month + day

            // 判断目录是否存在，没有则创建
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, {
                    recursive: true
                })
            }
            // dir就是上传文件存放的目录
            callback(null, dir)
        },
        // 设置文件名称
        filename: function (req, file, callback) {
            let fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname)
            // fileName就是上传文件的文件名
            callback(null, fileName)
        }
    })
})

// 上传
router.post('/pdf01', upload.single('file'), async function (req, res, next) {
    let result = {}
    try {
        // console.log(req.file)
        // console.log(path.resolve(__dirname, '../' + path.normalize(req.file.path)))
        // let pdfImage = new PDFImage(path.resolve(__dirname, '../' + path.normalize(req.file.path)))
        // pdfImage.convertPage(0).then(function(imagePath) {
        //     console.log(imagePath)
        //     // res.sendFile(imagePath)
        // }, function(err) {
        //     console.log(err)
        // })

        // res.setHeader('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
        // res.setHeader("Content-Disposition", "attachment; filename=11.txt");
        // res.end(result, 'binary');

        // multipart/form-data

        result.data = '11'
        result.success = true
    } catch (err) {
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 文件上传
router.post('/uploadFile', async function (req, res, next) {

    let result = {}
    try {
        let file = req.files[0]
        let oldName = file.path;//获取名字
        console.log('test', file);
        let newName = 'download\\' + file.originalname

        fs.rename(oldName, newName, (err) => {

            if (err) {
                result = {
                    "code": 400,
                    "message": err.message
                }
            } else {
                result = {
                    "code": 200,
                    "message": ""
                }
            }
        })

    } catch (err) {
        result = {
            "code": 400,
            "message": err.message
        }
    }
    res.json(result)
})

// 文件下载
router.get('/downloadFile', async function (req, res, next) {

    let result = {}
    try {

        let path = './download/' + req.query.filename
        let encodename = encodeURIComponent(req.query.filename)
        if (fs.existsSync(path)) {
            // 创建可读流，读取当前项目目录下的文件
            var rs = fs.createReadStream(path);

            // 设置响应请求头，200表示成功的状态码，headers表示设置的请求头
            res.writeHead(200, {
                'Content-Type': 'application/octet-stream',
                'Content-Disposition': 'attachment; filename=' + encodename
            });
            // 将可读流传给响应对象response 
            rs.pipe(res);

        }
        else {

            result = {
                "code": 400,
                "message": '文件不存在'
            }
            res.json(result)
        }

    } catch (err) {

        result = {
            "code": 400,
            "message": err.message
        }
        res.json(result)
    }

})
module.exports = router
